package com.copd.controller;

import com.copd.common.Result;
import com.copd.dto.PermissionDTO;
import com.copd.entity.Permission;
import com.copd.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "权限管理")
@RestController
@RequestMapping("/api/permissions")
@PreAuthorize("hasRole('ADMIN')")
public class PermissionController {
    
    @Autowired
    private PermissionService permissionService;
    
    @ApiOperation("获取所有权限")
    @GetMapping
    public Result<List<Permission>> getAllPermissions() {
        return Result.success("获取权限列表成功", permissionService.getAllPermissions());
    }
    
    @ApiOperation("根据ID获取权限")
    @GetMapping("/{permissionId}")
    public Result<Permission> getPermissionById(@PathVariable Integer permissionId) {
        Permission permission = permissionService.getPermissionById(permissionId);
        if (permission != null) {
            return Result.success("获取权限成功", permission);
        }
        return Result.error("404", "权限不存在");
    }
    
    @ApiOperation("创建权限")
    @PostMapping
    public Result<Permission> createPermission(@RequestBody PermissionDTO permissionDTO) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionDTO, permission);
        Permission createdPermission = permissionService.createPermission(permission);
        if (createdPermission != null) {
            return Result.success("创建权限成功", createdPermission);
        }
        return Result.error("500", "创建权限失败");
    }
    
    @ApiOperation("更新权限")
    @PutMapping("/{permissionId}")
    public Result<Permission> updatePermission(@PathVariable Integer permissionId, @RequestBody PermissionDTO permissionDTO) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionDTO, permission);
        permission.setPermissionId(permissionId);
        Permission updatedPermission = permissionService.updatePermission(permission);
        if (updatedPermission != null) {
            return Result.success("更新权限成功", updatedPermission);
        }
        return Result.error("500", "更新权限失败");
    }
    
    @ApiOperation("删除权限")
    @DeleteMapping("/{permissionId}")
    public Result<Boolean> deletePermission(@PathVariable Integer permissionId) {
        boolean deleted = permissionService.deletePermission(permissionId);
        if (deleted) {
            return Result.success("删除权限成功", true);
        }
        return Result.error("500", "删除权限失败");
    }
} 